<template>
    <div class="app-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="部门名称">
                <el-input size="mini" v-model="queryParams.deptName" placeholder="部门名称"></el-input>
            </el-form-item>
            <el-form-item label="负责人">
                <el-input size="mini" v-model="queryParams.leader" placeholder="负责人名字"></el-input>
            </el-form-item>
            <el-form-item label="负责人电话">
                <el-input size="mini" v-model="queryParams.phone" placeholder="负责人电话"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select size="mini" v-model="queryParams.status" placeholder="状态">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" @click="handleQuery">查询</el-button>
                <el-button size="mini" @click="handleResetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    <el-row :gutter="5">
        <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini">添加</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button icon="el-icon-delete" type="danger" @click="handleDelete" size="mini">删除选中</el-button>
        </el-col>
    </el-row>
    <el-table
            :data="tableData"
            stripe
            border
            row-key="deptId"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :cell-style="{padding:'3px'}"
    >
        <el-table-column type="selection" width="55"></el-table-column>
<!--        <el-table-column prop="deptId" label="部门id"></el-table-column>-->
<!--        <el-table-column prop="parentId" label="父部门id"></el-table-column>-->
        <el-table-column prop="deptName" label="部门名称"></el-table-column>
        <el-table-column prop="leader" label="负责人"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="部门状态">
            <template slot-scope="scope">
                <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                ></el-switch>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="160">
            <template slot-scope="scope">
                <el-tooltip content="修改" placement="top">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                    <el-button @click="handleDeleteRow(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
                </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
   <!-- <el-pagination
            layout="total, prev, pager, next"
            v-show="total>0"
            :total="total"
            :page-size="queryParams.limit"
            @current-change="handleCurrentChange">
    </el-pagination>-->

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
<!--                <el-col :span="12">-->
<!--                    <el-form-item label="父部门id" prop="parentId">-->
<!--                        <el-input v-model="form.parentId" placeholder="请输入上级部门" maxlength="20" />-->
<!--                    </el-form-item>-->
<!--                </el-col>-->
                <el-col :span="12">
                    <el-form-item label="上级部门" prop="parentId">
                        <treeselect v-model="form.parentId" :normalizer="normalizer" :options="deptOptions" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="部门名称" prop="deptName">
                        <el-input v-model="form.deptName" placeholder="请输入部门名称" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="负责人" prop="leader">
                        <el-input v-model="form.leader" placeholder="请输入负责人姓名" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="30" />
                    </el-form-item>
                </el-col>


            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
    </div>
</template>
<script>
    import {del,get,add,update,listAll} from "@/api/system/dept";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
        name: "Dept",
        components: { Treeselect },
        data() {
            return {
                queryParams: {
                    page: 1,
                    limit: 10
                },
                total: 0,
                tableData: [],
                multipleSelection: [],
                title: '',
                deptOptions: [],
                // 添加/修改表单参数
                form: {
                },
                // 添加/修改表单校验
                rules: {
                    /*parentId: [
                        {required: true, message: "上级部门不能为空", trigger: "blur"}
                    ],*/
                    deptName: [
                        {required: true, message: "部门名称不能为空", trigger: "blur"}
                    ],
                    leader: [
                        {required: true, message: "负责人不能为空", trigger: "blur"}
                    ],
                    email: [
                        {required: true, message: "邮箱不能为空", trigger: "blur"},
                        {type: 'email', message: "请输入正确邮箱", trigger: "blur"}
                    ],
                    phone: [
                        {required: true, message: "手机号码不能为空", trigger: "blur"},
                        {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
                    ]
                },
                // 是否显示弹出层
                open: false,
            }
        },
        created() {
            this.getList()
        },
        watch: {
            // 删除最后一页所有数据时，回到上一页
            total(val) {
                if(val == (this.queryParams.page-1) * this.queryParams.limit){
                    this.queryParams.page--
                    this.getList()
                }
            }
        },
        methods: {
            handleQuery() {
                listAll(this.queryParams).then(response => {
                    this.tableData = this.handleTree(response.data, "deptId")
                })
            },
            handleResetQuery() {
                this.queryParams = {
                    limit: 10,
                    page: 1,
                    deptName: undefined,
                    leader: undefined,
                    phone: undefined,
                    status: undefined
                }
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            reset() {
                this.form = {
                    deptId: undefined,
                    deptName: undefined,
                    leader: undefined,
                    phone: undefined,
                    email: undefined,
                    parentId: undefined
                }
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if(valid) {
                        if(this.form.deptId != undefined) {
                            update(this.form).then(()=>{
                                this.$message({message:'修改成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        } else {
                            add(this.form).then(()=>{
                                this.$message({message:'添加成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        }
                    }
                })
            },
            getList() {
                /*list(this.queryParams).then(response => {
                    this.tableData = this.handleTree(response.data.records, "deptId")
                    this.total = response.data.total
                })*/
                // 部门不分页，使用tree table
                listAll().then(response => {
                    this.tableData = this.handleTree(response.data, "deptId")
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
                console.log(this.multipleSelection);
            },
            handleCurrentChange(val) {
                this.queryParams.page = val;
                this.getList()
            },
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加部门";
                listAll().then(resp=>{
                    this.deptOptions = this.handleTree(resp.data, "deptId")
                })
            },
            /** 转换部门数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.deptId,
                    label: node.deptName,
                    children: node.children
                };
            },
            handleView(row) {
                get(row.deptId).then(resp=>{
                    console.log(resp);
                })
            },
            handleEdit(row) {
                this.reset();
                listAll().then(resp=>{
                    this.deptOptions =  this.handleTree(resp.data, "deptId")
                })
                get(row.deptId).then(resp=>{
                    this.form = resp.data;
                    if(this.form.parentId==0) this.form.parentId = null
                    this.open = true;
                    this.title = "修改部门";
                })
            },
            handleDeleteRow(row) {
                this.$confirm('确定删除"' + row.deptName + '"吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let idList = row.deptId;
                    del(idList).then(resp => {
                        this.$message({
                            type: 'success',
                            message: resp.msg
                        });
                        this.getList()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleDelete() {
                if(this.multipleSelection.length == 0) {
                    this.$alert('请至少选中一条记录')
                } else {
                    this.$confirm('确定删除选中的记录吗, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let idList = this.multipleSelection.map(row=>row.deptId).join(",");
                        del(idList).then(resp => {
                            this.$message({
                                type: 'success',
                                message: resp.msg
                            });
                            this.getList()
                        })

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$confirm('确认要"' + text + '""' + row.deptName + '"部门吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return update({deptId:row.deptId, status:row.status});
                }).then(() => {
                    this.$message(text + "成功");
                }).catch(function() {
                    row.status = row.status === "0" ? "1" : "0";
                });
            }
        }
    }
</script>
